<template>
  <div class="home_container  p-r-20px w-100%" >
    <div class="home_top ">
            <div class="left">
              <HomeLeft />
            </div>
            <div class="center">
              <HomeMiddle  />
            </div>
             <div class="right">
              <HomeRight />
            </div>
    </div>
    <div class="w-100% home_bottom" :style="{ marginTop: computedMarginTop + 'px' }">
      <MCard>
        <template #header>      
          <span>{{ t('home.traffic_information_label') }}</span>
        </template>
        <div >
          <div v-for="(_,key) in dnnSpeedInfo" :key="key" class="w-100%">
            <div class="w-100% flex justify-center">
                <div class="traffic-info-container">
                  <div class="traffic-info-item">
                    <div class="traffic-info-label">
                      <i class="el-icon-upload2"></i>
                      <span>发送速率</span>
                    </div>
                    <div class="traffic-info-value">{{ currentDnnSpeedInfo[key].tx_bytes_ps }}MB/s</div>
                  </div>
                  <div class="traffic-info-divider"></div>
                  <div class="traffic-info-item">
                    <div class="traffic-info-label">
                      <i class="el-icon-download"></i>
                      <span>接收速率</span>
                    </div>
                    <div class="traffic-info-value">{{ currentDnnSpeedInfo[key].rx_bytes_ps }}MB/s</div>
                  </div>
                  <div class="traffic-info-divider"></div>
                  <div class="traffic-info-item">
                    <div class="traffic-info-label">
                      <i class="el-icon-time"></i>
                      <span>当前时间</span>
                    </div>
                    <div class="traffic-info-value time-value">{{ currentDnnSpeedInfo[key].time }}</div>
                  </div>
                  <div class="time-decoration"></div>
                </div>
            </div>
             <LineCharts :lineData="dnnSpeedInfo[key]" :name="String(key)" :type="dnnSpeedInfo[key].type" />
          </div>
        </div>
    </MCard>
    </div>  
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  name: 'Home',
})
</script>

<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import HomeLeft from './homeLeft/index.vue'
import HomeMiddle from './homeMiddle/index.vue'
import HomeRight from './homeRight/index.vue'
import { DnnConfigApi } from '@/api/dnnConfig'
import LineCharts from '@/components/Echarts/LineCharts.vue'
import dayjs from 'dayjs'
import { getWebSocketInstance } from '@/utils/websocketExample'
const ws = getWebSocketInstance()
const { t } = useI18n()
const dnnSpeedInfo = ref<any>({})
const currentDnnSpeedInfo = ref<any>({})
const dnnType = ['internet','xwtj','caa']
// 根据DNN名称获取类型的映射关系
const getDnnTypeByName = (name: string) => {
  if (name.includes('internet')) return 'internet'
  if (name.includes('xwtj')) return 'xwtj' 
  if (name.includes('caa')) return 'caa'
  if (name.includes('private_net')) return 'private_net'
  if (name.includes('language')) return 'language'
  return 'unknown'
}
async function getDnnInfo(){
  const {data} = await DnnConfigApi.reqGetDnnInfo()
  data.list = data.list.filter((item:any)=>dnnType.includes(item.type)).sort((a:any,b:any)=>{
    return a.type === 'internet' ? -1 : 1
  })
  dnnSpeedInfo.value = data.list.reduce((acc:any,item:any)=>{
    acc[item.name] = {
      tx_bytes_ps:[],
      rx_bytes_ps:[],
      timeList:[],
      type:item.type
    }
    currentDnnSpeedInfo.value[item.name] = {
      tx_bytes_ps:0,
      rx_bytes_ps:0,
      time:'',
      type:item.type
    }
    return acc
  },{})  
}

// 处理WebSocket推送的DNN速度数据
function handleDnnSpeedData(data: any) {
  if (!data.speed_list || !Array.isArray(data.speed_list)) {
    console.warn('WebSocket推送的DNN速度数据格式错误:', data)
    return
  }
  const currentTime = dayjs().format('HH:mm:ss')
  data.speed_list.forEach((speedData: any) => {
    const { name, tx_bytes_ps, rx_bytes_ps } = speedData
    // 如果dnnSpeedInfo中还没有该DNN的数据，则初始化
    if (!dnnSpeedInfo.value[name]) {
      const dnnType = getDnnTypeByName(name)
      dnnSpeedInfo.value[name] = {
        tx_bytes_ps: [],
        rx_bytes_ps: [],
        timeList: [],
        type: dnnType
      }
      currentDnnSpeedInfo.value[name] = {
        tx_bytes_ps: 0,
        rx_bytes_ps: 0,
        time: '',
        type: dnnType
      }
    }
    // 限制数组长度为10个数据点
    if (dnnSpeedInfo.value[name].tx_bytes_ps.length >= 10) {
      dnnSpeedInfo.value[name].tx_bytes_ps.shift()
      dnnSpeedInfo.value[name].rx_bytes_ps.shift()
      dnnSpeedInfo.value[name].timeList.shift()
    }
    // 转换单位并添加新数据点
    const txSpeedMB = (tx_bytes_ps / 1024 / 1024).toFixed(6)
    const rxSpeedMB = (rx_bytes_ps / 1024 / 1024).toFixed(6)
    dnnSpeedInfo.value[name].tx_bytes_ps.push(Number(txSpeedMB))
    dnnSpeedInfo.value[name].rx_bytes_ps.push(Number(rxSpeedMB))
    dnnSpeedInfo.value[name].timeList.push(currentTime)
    // 更新当前速度信息
    currentDnnSpeedInfo.value[name].tx_bytes_ps = txSpeedMB
    currentDnnSpeedInfo.value[name].rx_bytes_ps = rxSpeedMB
    currentDnnSpeedInfo.value[name].time = currentTime
  })
}
const computedMarginTop = ref(100);
const updateMarginTop = () => {
  // 获取顶部区域的高度
  const topElement = document.querySelector('.home_top');
  if (topElement) {
    // 计算适当的边距，可以是顶部元素高度加上一些额外的空间
    const topHeight = topElement.getBoundingClientRect().height;
    // 设置边距为顶部元素高度的10%，或者根据需要调整此计算
    computedMarginTop.value = Math.max(20, Math.min(100, topHeight * 0.1))+10; 
  }
};
const wsTaskData:any = {
  'ap_net_host_speed_get': handleDnnSpeedData,
}
// 接受ws消息的函数
function handleWsMessage(response:any){
  const {cmd,data} = response
  if(wsTaskData[cmd]){
    wsTaskData[cmd](data)
  }
}
ws.on('message',handleWsMessage)
const handleResize = () => {
  updateMarginTop();
};
onMounted(async()=>{
  updateMarginTop(); 
  window.addEventListener('resize', handleResize);
  await getDnnInfo();
})
onBeforeUnmount(()=>{
  window.removeEventListener('resize', handleResize);
})
</script>
<style lang="scss" scoped>
@import '@/styles/pageLabel.scss';
@import '@/styles/form.scss';
@import '@/styles/table.scss';
@import '@/styles/card.scss';
.home_container {
  .home_top {
    width: 100%;
    height: 900px;
    position: relative;
      .left{
        width: 450px;
        height: 100%;
        top: 0;
        left: 0;
        position: absolute;
        z-index: 901;
      }
      .center{
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        z-index: 900;
      }
      .right{
        width: 450px;
        height: 100%;
        position: absolute;
        top: 0;
        right: 0;
        z-index: 901; 
    }
  }
  .home_bottom {


    .traffic-info-container {
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(90deg, rgba(4, 32, 84, 0.2) 0%, rgba(13, 78, 141, 0.3) 50%, rgba(4, 32, 84, 0.2) 100%);
      border: 1px solid rgba(23, 157, 223, 0.3);
      border-radius: 4px;
      padding: 8px 20px;
      margin-bottom: 10px;
      position: relative;
      box-shadow: 0 0 10px rgba(0, 209, 237, 0.2);
      
      &::before, &::after {
        content: '';
        position: absolute;
        width: 10px;
        height: 10px;
        border: 1px solid rgba(23, 157, 223, 0.8);
      }
      
      &::before {
        top: -1px;
        left: -1px;
        border-right: none;
        border-bottom: none;
      }
      
      &::after {
        top: -1px;
        right: -1px;
        border-left: none;
        border-bottom: none;
      }
      
      .traffic-info-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 0 20px;
        
        .traffic-info-label {
          display: flex;
          align-items: center;
          color: #FFFFFF;
          font-size: 14px;
          margin-bottom: 5px;
          
          i {
            margin-right: 5px;
            color: #38B0D5;
          }
        }
        
        .traffic-info-value {
          color: #00AAFF;
          font-size: 16px;
          font-weight: bold;
          text-shadow: 0 0 5px rgba(0, 170, 255, 0.5);
          
          &.time-value {
            color: #00E676;
            position: relative;
            padding: 0 5px;
            
            &::before, &::after {
              content: '';
              position: absolute;
              height: 4px;
              width: 4px;
              background-color: #00E676;
              top: 50%;
              transform: translateY(-50%);
              border-radius: 50%;
              box-shadow: 0 0 4px #00E676;
            }
            
            &::before {
              left: -4px;
            }
            
            &::after {
              right: -4px;
            }
          }
        }
      }
      
      .traffic-info-divider {
        width: 1px;
        height: 30px;
        background: linear-gradient(to bottom, transparent, rgba(23, 157, 223, 0.8), transparent);
        margin: 0 10px;
      }
      
      .time-decoration {
        position: absolute;
        bottom: -1px;
        left: 50%;
        transform: translateX(-50%);
        width: 40%;
        height: 1px;
        background: linear-gradient(to right, transparent, rgba(0, 230, 118, 0.8), transparent);
        
        &::before, &::after {
          content: '';
          position: absolute;
          bottom: 0;
          width: 5px;
          height: 5px;
          background-color: rgba(0, 230, 118, 0.8);
          border-radius: 50%;
          box-shadow: 0 0 5px rgba(0, 230, 118, 0.8);
        }
        
        &::before {
          left: 10%;
          animation: pulse 2s infinite alternate;
        }
        
        &::after {
          right: 10%;
          animation: pulse 2s infinite alternate-reverse;
        }
      }
    }
  }
}

@keyframes pulse {
  0% {
    opacity: 0.3;
    transform: scale(0.8);
  }
  100% {
    opacity: 1;
    transform: scale(1.2);
  }
}

.m-t-20 {
  margin-top: 20px;
}

.m-b-10px {
  margin-bottom: 10px;
}

.m-b-20px {
  margin-bottom: 20px;
}
</style>
